package vip.aning.gitsync.javafx;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.PasswordField;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.control.Tooltip;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;
import javafx.util.Duration;
import org.slf4j.LoggerFactory;
import vip.aning.gitsync.config.ConfigManager;
import vip.aning.gitsync.constant.AppConst;
import vip.aning.gitsync.data.SyncMessageListData;
import vip.aning.gitsync.job.GitJob;
import vip.aning.gitsync.service.GitClientService;
import vip.aning.gitsync.service.JobService;

import java.io.File;
import java.util.Timer;


public class MainApp extends Application {
    private final org.slf4j.Logger LOG = LoggerFactory.getLogger(this.getClass());
    private Timer timer;
    private boolean isTimerCancelled = false;

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("git文件自动拉推");

        // 加载提示组件
        ProgressIndicator loadingIndicator = new ProgressIndicator();
        Label loadingText = new Label("加载中...");
        // 使用 StackPane 叠加加载提示和文本
        StackPane loadingPane = new StackPane(loadingIndicator, loadingText);
        loadingPane.setVisible(false);

        // 创建网格布局
        GridPane grid = new GridPane();
        grid.setPadding(new Insets(10, 10, 10, 10));
        grid.setVgap(10);
        grid.setHgap(10);

        // 设置列约束，让第二列（文本框列）填满窗口
        ColumnConstraints col1 = new ColumnConstraints();
        ColumnConstraints col2 = new ColumnConstraints();
        // 第二列自动扩展
        col2.setHgrow(Priority.ALWAYS);
        grid.getColumnConstraints().addAll(col1, col2);

        Label gitUrlLabel = new Label("git地址:");
        TextField gitUrlField = new TextField();
        // gitUrlField.setText("https://github.com/liangxianning/js-exercise01.git");
        gitUrlField.setText("https://gitee.com/xnhub/javabage.git");
        gitUrlField.setMaxWidth(Double.MAX_VALUE);
        grid.add(gitUrlLabel, 0, 0);
        grid.add(gitUrlField, 1, 0);
        // 合并第二列及后面的所有列
        GridPane.setColumnSpan(gitUrlField, 2);


        Label gitBranchLabel = new Label("分支:");
        TextField gitBranchField = new TextField();
        grid.add(gitBranchLabel, 0, 1);
        grid.add(gitBranchField, 1, 1);
        gitBranchField.setText("master");
        gitBranchField.setMinWidth(200);
        gitBranchField.setMaxWidth(200);

        // 创建单选按钮
        RadioButton remoteButton = new RadioButton("远程");
        remoteButton.setUserData(AppConst.remote);
        // 创建问号图标
        ImageView remoteButtonIcon = new ImageView(
                new Image(getClass().getResource("/icons/help.png").toExternalForm()));
        remoteButtonIcon.setFitWidth(16); // 设置图标宽度
        remoteButtonIcon.setFitHeight(16); // 设置图标高度
        Tooltip remoteButtonTip = new Tooltip("当发生冲突时，直接用远程的覆盖本地的，冲突的文件在本地的修改会丢失");
        remoteButtonTip.setShowDelay(Duration.millis(10)); // 延迟 500 毫秒显示
        remoteButtonTip.setHideDelay(Duration.millis(10)); // 延迟 200 毫秒隐藏
        remoteButtonTip.setShowDuration(Duration.seconds(30)); // 显示 5 秒后隐藏
        Tooltip.install(remoteButtonIcon, remoteButtonTip); // 将 Tooltip 安装到 Label 上

        RadioButton localButton = new RadioButton("本地");
        localButton.setUserData(AppConst.local);
        ImageView localButtonIcon = new ImageView(
                new Image(getClass().getResource("/icons/help.png").toExternalForm()));
        localButtonIcon.setFitWidth(16); // 设置图标宽度
        localButtonIcon.setFitHeight(16); // 设置图标高度
        Tooltip localButtonTip = new Tooltip("当发生冲突时，直接用本地的覆盖远程的，本地文件推到远程后覆盖远程文件");
        localButtonTip.setShowDelay(Duration.millis(10)); // 延迟 500 毫秒显示
        localButtonTip.setHideDelay(Duration.millis(10)); // 延迟 200 毫秒隐藏
        localButtonTip.setShowDuration(Duration.seconds(30)); // 显示 5 秒后隐藏
        Tooltip.install(localButtonIcon, localButtonTip); // 将 Tooltip 安装到 Label 上

        // 创建 ToggleGroup 并将单选按钮加入组
        ToggleGroup localRemoteGroup = new ToggleGroup();
        remoteButton.setToggleGroup(localRemoteGroup);
        localButton.setToggleGroup(localRemoteGroup);
        // 监听选择变化
        localRemoteGroup.selectedToggleProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue != null) {
                // 获取选中的 RadioButton 的值
                String selectedValue = (String) newValue.getUserData();
                ConfigManager.getInstance().getGitInfo().setSelectLocalOrRemote(selectedValue);
            }
        });

        // 设置默认选中项（可选）
        localButton.setSelected(true);

        HBox hbox = new HBox(5, localButton, localButtonIcon, remoteButton, remoteButtonIcon); // 设置间距为 5
        hbox.setAlignment(Pos.CENTER_LEFT); // 左对齐
        grid.add(hbox, 2, 1);

        Label gitAccountLabel = new Label("用户名:");
        TextField gitAccountField = new TextField();
        // gitAccountField.setText("liangxianning");
        gitAccountField.setText("398304357@qq.com");
        grid.add(gitAccountLabel, 0, 2);
        grid.add(gitAccountField, 1, 2);
        gitAccountField.setMinWidth(200);
        gitAccountField.setMaxWidth(200);

        Label passwordLabel = new Label("密码:");
        PasswordField passwordField = new PasswordField();
        // passwordField.setText("lxn@github31415926.");
        passwordField.setText("lxn31415926");
        grid.add(passwordLabel, 0, 3);
        grid.add(passwordField, 1, 3);
        passwordField.setMinWidth(200);
        passwordField.setMaxWidth(200);

        // 选择目录按钮
        Label dirLabel = new Label("同步目录:");
        TextField localPathField = new TextField("未选择目录");
        // localPathField.setText("H:\\Workspace\\IdeaProjects\\aa");
        localPathField.setText("H:\\Workspace\\IdeaProjects\\giteebb");
        localPathField.setEditable(false);
        Button chooseDirButton = new Button("选择目录");
        grid.add(dirLabel, 0, 4);
        grid.add(localPathField, 1, 4);
        grid.add(chooseDirButton, 2, 4);

        Label gitCommitMessageLabel = new Label("提交信息:");
        TextField gitCommitMessageField = new TextField();
        gitCommitMessageField.setText("自动同步");
        grid.add(gitCommitMessageLabel, 0, 5);
        grid.add(gitCommitMessageField, 1, 5);
        gitCommitMessageField.setMinWidth(200);
        gitCommitMessageField.setMaxWidth(Double.MAX_VALUE);

        Label authorNameLabel = new Label("作者（可选）:");
        TextField authorNameField = new TextField();
        grid.add(authorNameLabel, 0, 6);
        grid.add(authorNameField, 1, 6);
        authorNameField.setMinWidth(200);
        authorNameField.setMaxWidth(200);

        Label authorEmailLabel = new Label("作者邮箱（可选）:");
        TextField authorEmailField = new TextField();
        grid.add(authorEmailLabel, 0, 7);
        grid.add(authorEmailField, 1, 7);
        authorEmailField.setMinWidth(200);
        authorEmailField.setMaxWidth(200);

        chooseDirButton.setOnAction(event -> {
            DirectoryChooser directoryChooser = new DirectoryChooser();
            directoryChooser.setTitle("选择目录");
            File selectedDirectory = directoryChooser.showDialog(primaryStage);
            if (selectedDirectory != null) {
                localPathField.setText(selectedDirectory.getAbsolutePath());
            } else {
                localPathField.setText("未选择目录");
            }
        });

        // 提交按钮
        Button submitButton = new Button("开启自动拉推");
        Button cancelButton = new Button("关闭自动拉推");
        cancelButton.setDisable(true);
        // 设置按钮之间的间距为 10
        HBox buttonBox = new HBox(10);
        // 使用 HBox 将按钮放在同一行
        buttonBox.getChildren().addAll(submitButton, cancelButton);
        grid.add(buttonBox, 1, 8);

        // 列表组件
        VBox vbox = new VBox(10, grid, new Label("同步记录:"), createListView());
        vbox.setPadding(new Insets(10, 10, 10, 10));

        // 提交按钮事件
        submitButton.setOnAction(event -> {
            String gitUrl = gitUrlField.getText();
            String gitBranch = gitBranchField.getText();
            String authorName = authorNameField.getText();
            String authorEmail = authorEmailField.getText();
            String gitCommitMessage = gitCommitMessageField.getText();
            String gitAccount = gitAccountField.getText();
            String password = passwordField.getText();
            String selectedDir = localPathField.getText();
            // 验证用户名不能为空
            if (gitUrl.isEmpty()) {
                JavaFxDialog.alert("错误", "git仓库地址不能为空");
                return;
            }

            if (gitBranch.isEmpty()) {
                JavaFxDialog.alert("错误", "git分支不能为空");
                return;
            }

            if (gitCommitMessage.isEmpty()) {
                JavaFxDialog.alert("错误", "提交信息不能为空");
                return;
            }

            if (gitAccount.isEmpty()) {
                JavaFxDialog.alert("错误", "用户名不能为空");
                return;
            }

            if (password.isEmpty()) {
                JavaFxDialog.alert("错误", "密码不能为空");
                return;
            }

            if (selectedDir.isEmpty() || "未选择目录".equals(selectedDir)) {
                JavaFxDialog.alert("错误", "未选择目录");
                return;
            }

            SyncMessageListData.clean();
            setControlsDisable(gitUrlField,
                    gitBranchField,
                    gitAccountField,
                    passwordField,
                    authorNameField,
                    authorEmailField,
                    gitCommitMessageField,
                    localPathField,
                    chooseDirButton,
                    submitButton,
                    cancelButton,
                    localButton,
                    remoteButton,
                    true);

            // 将 gitInfo 对象存储到全局配置中
            ConfigManager.getInstance().getGitInfo().setRepoUrl(gitUrl)
                    .setBranch(gitBranch)
                    .setUsername(gitAccount)
                    .setPassword(password)
                    .setAuthorName(authorName)
                    .setAuthorEmail(authorEmail)
                    .setCommitMessage(gitCommitMessage)
                    .setLocalPath(selectedDir);

            GitClientService gitClientService = new GitClientService();
            gitClientService.isValidRepository(loadingPane, loadingText);

            JobService.addJob(GitJob.class, "0 0/1 * * * ?");
        });

        cancelButton.setOnAction(event -> {
            JavaFxDialog.alert("信息", "关闭自动拉推成功！");

            setControlsDisable(gitUrlField,
                    gitBranchField,
                    gitAccountField,
                    passwordField,
                    authorNameField,
                    authorEmailField,
                    gitCommitMessageField,
                    localPathField,
                    chooseDirButton,
                    submitButton,
                    cancelButton,
                    localButton,
                    remoteButton,
                    false);

            JobService.removeGitSyncJob();
        });

        // 使用 StackPane 叠加加载提示
        StackPane root = new StackPane(vbox, loadingPane);
        root.setStyle("-fx-alignment: center;");

        // 创建场景并设置到舞台
        createScene(primaryStage, root);
    }

    private static ListView<String> createListView() {
        ListView<String> listView = new ListView<>();
        listView.setItems(SyncMessageListData.dataList);
        listView.setCellFactory(lv -> new ListCell<>() {
            private final Label label;

            {
                label = new Label();
                label.setWrapText(true); // 启用自动换行
                label.setMinWidth(480); // 设置最大宽度，超过此宽度时换行
                label.setMaxWidth(480); // 设置最大宽度，超过此宽度时换行
            }

            @Override
            protected void updateItem(String item, boolean empty) {
                super.updateItem(item, empty);

                label.setText(item);
                setGraphic(label);
                if (!empty && item != null && item.startsWith("Error:")) {
                    setStyle("-fx-background-color: red; -fx-text-fill: white;");
                } else {
                    setStyle(""); // 清除样式
                }
            }
        });
        return listView;
    }

    private static void setControlsDisable(TextField gitUrlField,
                                           TextField gitBranchField,
                                           TextField gitAccountField,
                                           PasswordField passwordField,
                                           TextField authorNameField,
                                           TextField authorEmailField,
                                           TextField gitCommitMessageField,
                                           TextField localPathField,
                                           Button chooseDirButton,
                                           Button submitButton,
                                           Button cancelButton,
                                           RadioButton localButton,
                                           RadioButton remoteButton,
                                           boolean disable) {
        gitUrlField.setDisable(disable);
        gitBranchField.setDisable(disable);
        gitAccountField.setDisable(disable);
        passwordField.setDisable(disable);

        authorNameField.setDisable(disable);
        authorEmailField.setDisable(disable);
        gitCommitMessageField.setDisable(disable);
        localPathField.setDisable(disable);
        chooseDirButton.setDisable(disable);

        submitButton.setDisable(disable);
        cancelButton.setDisable(!disable);
        localButton.setDisable(disable);
        remoteButton.setDisable(disable);
    }

    private static void createScene(Stage primaryStage, StackPane root) {
        double minH = 500;
        double maxH = 700;
        double minW = 550;
        double maxW = 1000;
        Scene scene = new Scene(root, minH, minW);
        primaryStage.setScene(scene);
        // 设置窗口最小宽度为 550
        primaryStage.setMinWidth(minW);
        primaryStage.setMaxWidth(maxW);
        primaryStage.setMinHeight(minH);
        primaryStage.setMaxHeight(maxH);
        primaryStage.show();
    }

    // 方法：将电话号码中间部分用 * 号代替
    private String maskPwd(String pwd) {
        if (pwd.length() < 7) {
            return pwd.substring(0, pwd.length() / 2) + "****";
        }
        String prefix = pwd.substring(0, 3);
        String suffix = pwd.substring(pwd.length() - 3);
        return prefix + "****" + suffix;
    }

    public static void main(String[] args) {
        launch(args);
    }
}
